<template>
  <div>
    <h2>工序管理</h2>
    
    <!-- 查询区域 -->
    <div class="search-container">
      <el-select v-model="searchType" style="width: 150px; margin-right: 10px">
        <el-option label="工序ID" value="operationId" />
        <el-option label="工艺路线ID" value="routeId" />
        <el-option label="机器类型ID" value="machineTypeId" />
      </el-select>
      <el-input
        v-model="searchQuery"
        :placeholder="`请输入${searchTypeLabel}进行查询`"
        clearable
        @keyup.enter="searchOperation"
        style="width: 300px; margin-right: 10px"
      />
      <el-button type="primary" @click="searchOperation" :loading="loading">查询</el-button>
      <el-button @click="resetSearch">重置</el-button>
    <el-button type="primary" @click="showAddOperationDialog">添加工序</el-button>
    </div>
    
    <!-- 工序表格 -->
    <el-table 
      :data="operations" 
      style="width: 100%" 
      v-loading="loading"
      border
      stripe
    >
              <el-table-column prop="operationId" label="工序ID" width="150" show-overflow-tooltip sortable />
        <el-table-column prop="routeId" label="工艺路线ID" width="150" show-overflow-tooltip sortable />
        <el-table-column prop="operationCode" label="工序编号" width="120" sortable />
        <el-table-column prop="operationName" label="工序名称" width="150" show-overflow-tooltip sortable />
        <el-table-column prop="machineTypeName" label="机器类型" width="150" show-overflow-tooltip sortable />
        <el-table-column prop="standardTime" label="标准时间(分钟)" width="130" sortable />
        <el-table-column prop="sequenceNo" label="工序顺序" width="100" sortable />
        <el-table-column prop="predecessorOps" label="前置工序" width="120" show-overflow-tooltip sortable />
      <el-table-column label="原料数量" width="100">
        <template #default="scope">
          {{ scope.row.materials ? scope.row.materials.length : 0 }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="editOperation(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteOperation(scope.row)">删除</el-button>
          <el-button size="small" type="info" @click="viewMaterials(scope.row)">原料</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 工序编辑对话框 -->
    <el-dialog v-model="showDialog" :title="dialogTitle" width="70%">
      <el-form 
        ref="operationFormRef"
        :model="formData" 
        :rules="formRules"
        label-width="140px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
        <el-form-item label="工序ID" v-if="isEdit">
          <el-input v-model="formData.operationId" disabled />
        </el-form-item>
            <el-form-item label="工艺路线" prop="routeId">
              <el-select 
                v-model="formData.routeId" 
                placeholder="请选择工艺路线"
                filterable
                style="width: 100%"
                :disabled="isEdit"
                @change="onRouteChange"
              >
                <el-option
                  v-for="route in allRoutes"
                  :key="route.routeId"
                  :label="`${route.routeName} (${route.productName})`"
                  :value="route.routeId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="工序编号" prop="operationCode">
              <el-input 
                v-model="formData.operationCode" 
                placeholder="请输入工序编号"
                maxlength="50"
              />
            </el-form-item>
            <el-form-item label="工序名称" prop="operationName">
              <el-input 
                v-model="formData.operationName" 
                placeholder="请输入工序名称"
                maxlength="100"
              />
        </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所需机器类型" prop="machineTypeId">
              <el-select 
                v-model="formData.machineTypeId" 
                placeholder="请选择机器类型"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="type in allMachineTypes"
                  :key="type.machineTypeId"
                  :label="type.typeName"
                  :value="type.machineTypeId"
                />
              </el-select>
        </el-form-item>
            <el-form-item label="标准作业时间" prop="standardTime">
              <el-input-number 
                v-model="formData.standardTime" 
                :min="1"
                :step="1"
                style="width: 100%"
                placeholder="请输入标准作业时间(分钟)"
              />
        </el-form-item>
            <el-form-item label="工序序号" prop="sequenceNo">
              <el-input-number 
                v-model="formData.sequenceNo" 
                :min="1"
                :step="1"
                style="width: 100%"
                placeholder="请输入工序序号"
              />
        </el-form-item>
        <el-form-item label="前置工序ID">
              <el-input 
                v-model="formData.predecessorOps" 
                placeholder="多个用逗号分隔"
                maxlength="200"
              />
        </el-form-item>
          </el-col>
        </el-row>

        <!-- 原料列表 -->
        <el-divider content-position="left">工序原料</el-divider>
        <div style="margin-bottom: 15px;">
          <el-button type="primary" size="small" @click="addMaterial">添加原料</el-button>
        </div>
        <el-table :data="formData.materials" border size="small">
          <el-table-column label="原料" width="200">
            <template #default="scope">
              <el-select 
                v-model="scope.row.materialId" 
                placeholder="请选择原料"
                filterable
                style="width: 100%"
                @change="(val) => onMaterialChange(val, scope.$index)"
              >
                <el-option
                  v-for="material in allMaterials"
                  :key="material.materialId"
                  :label="material.materialName"
                  :value="material.materialId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="materialName" label="原料名称" width="150" sortable />
          <el-table-column label="用量" width="120">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.quantity" 
                :min="0.01"
                :step="0.01"
                :precision="2"
                style="width: 100%"
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column label="单位" width="100">
            <template #default="scope">
              <el-input 
                v-model="scope.row.unit" 
                placeholder="单位"
                size="small"
                maxlength="10"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
              <el-button 
                size="small" 
                type="danger" 
                @click="removeMaterial(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="saveOperation" :loading="saveLoading">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 原料详情对话框 -->
    <el-dialog v-model="showMaterialsDialog" :title="`工序原料 - ${currentOperationName}`" width="60%">
      <el-table :data="currentMaterials" border>
        <el-table-column prop="materialName" label="原料名称" sortable />
        <el-table-column prop="quantity" label="用量" width="100" sortable />
        <el-table-column prop="unit" label="单位" width="80" sortable />
      </el-table>
      <template #footer>
        <el-button @click="showMaterialsDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

const API_BASE_URL = 'http://117.72.45.141:8091';

// 响应式数据
const operations = ref([]);
const allRoutes = ref([]);
const allMachineTypes = ref([]);
const allMaterials = ref([]);
const loading = ref(false);
const saveLoading = ref(false);
const searchType = ref('operationId');
const searchQuery = ref('');

// 对话框状态
const showDialog = ref(false);
const showMaterialsDialog = ref(false);
const isEdit = ref(false);
const dialogTitle = ref('添加工序');
const currentOperationName = ref('');
const currentMaterials = ref([]);

// 表单引用
const operationFormRef = ref(null);

// 表单数据
const formData = reactive({
  operationId: '',
  routeId: '',
  operationCode: '',
  operationName: '',
  machineTypeId: '',
  standardTime: 60,
  predecessorOps: '',
  sequenceNo: 1,
  materials: []
});

// 表单验证规则
const formRules = {
  routeId: [
    { required: true, message: '请选择工艺路线', trigger: 'change' }
  ],
  operationCode: [
    { required: true, message: '请输入工序编号', trigger: 'blur' },
    { min: 1, max: 50, message: '工序编号长度在 1 到 50 个字符', trigger: 'blur' },
    { validator: checkOperationCode, trigger: 'blur' }
  ],
  operationName: [
    { required: true, message: '请输入工序名称', trigger: 'blur' },
    { min: 1, max: 100, message: '工序名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  machineTypeId: [
    { required: true, message: '请选择机器类型', trigger: 'change' }
  ],
  standardTime: [
    { required: true, message: '请输入标准作业时间', trigger: 'blur' },
    { type: 'number', min: 1, message: '标准作业时间不能少于1分钟', trigger: 'blur' }
  ],
  sequenceNo: [
    { required: true, message: '请输入工序序号', trigger: 'blur' },
    { type: 'number', min: 1, message: '工序序号不能少于1', trigger: 'blur' },
    { validator: checkSequenceNo, trigger: 'blur' }
  ]
};

// 计算属性
const searchTypeLabel = computed(() => {
  const labels = {
    operationId: '工序ID',
    routeId: '工艺路线ID',
    machineTypeId: '机器类型ID'
  };
  return labels[searchType.value] || '信息';
});

// 检查工序编号是否重复
async function checkOperationCode(rule, value, callback) {
  if (!value || !formData.routeId) {
    callback();
    return;
  }
  
  try {
    const response = await axios.get(`${API_BASE_URL}/api/operation/check-code`, {
      params: {
        routeId: formData.routeId,
        operationCode: value,
        excludeId: isEdit.value ? formData.operationId : ''
      },
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      if (response.data.data === false) {
        callback(new Error('工序编号在该工艺路线中已存在'));
      } else {
        callback();
      }
    } else {
      callback();
    }
  } catch (error) {
    console.error('检查工序编号失败:', error);
    callback();
  }
}

// 检查工序序号是否重复
async function checkSequenceNo(rule, value, callback) {
  if (!value || !formData.routeId) {
    callback();
    return;
  }
  
  try {
    const response = await axios.get(`${API_BASE_URL}/api/operation/check-sequence`, {
      params: {
        routeId: formData.routeId,
        sequenceNo: value,
        excludeId: isEdit.value ? formData.operationId : ''
      },
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      if (response.data.data === false) {
        callback(new Error('工序序号在该工艺路线中已存在'));
      } else {
        callback();
      }
    } else {
      callback();
    }
  } catch (error) {
    console.error('检查工序序号失败:', error);
    callback();
  }
}

// 加载基础数据
const loadAllRoutes = async () => {
  try {
    // 这里需要实现获取所有工艺路线的接口，目前后端没有提供，先使用模拟数据
    allRoutes.value = [];
  } catch (error) {
    console.error('加载工艺路线失败:', error);
  }
};

const loadAllMachineTypes = async () => {
  try {
    const response = await axios.post(`${API_BASE_URL}/api/machine-type/page`, {
      pageNum: 1,
      pageSize: 1000
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.success) {
      allMachineTypes.value = response.data.data.records || [];
    }
  } catch (error) {
    console.error('加载机器类型失败:', error);
  }
};

const loadAllMaterials = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/material/all`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      allMaterials.value = response.data.data || [];
    }
  } catch (error) {
    console.error('加载原料列表失败:', error);
  }
};

// 工艺路线变化时触发
const onRouteChange = (routeId) => {
  // 清除工序编号和序号的验证
  if (operationFormRef.value) {
    operationFormRef.value.clearValidate(['operationCode', 'sequenceNo']);
  }
};

// 搜索工序
const searchOperation = async () => {
  if (!searchQuery.value.trim()) {
    ElMessage.warning('请输入搜索内容');
    return;
  }
  
  loading.value = true;
  try {
    let url = '';
    switch (searchType.value) {
      case 'operationId':
        url = `${API_BASE_URL}/api/operation/${searchQuery.value}`;
        break;
      case 'machineTypeId':
        url = `${API_BASE_URL}/api/operation/machine-type/${searchQuery.value}`;
        break;
      case 'routeId':
        url = `${API_BASE_URL}/api/operation/route/${searchQuery.value}`;
        break;
    }
    
    const response = await axios.get(url, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      operations.value = Array.isArray(response.data.data) 
        ? response.data.data 
        : response.data.data ? [response.data.data] : [];
        
      if (operations.value.length === 0) {
        ElMessage.info('没有找到匹配的工序');
      } else {
        ElMessage.success(`找到 ${operations.value.length} 个工序`);
      }
    } else {
      ElMessage.warning(response.data.message || '搜索失败');
      operations.value = [];
    }
  } catch (error) {
    console.error('搜索工序失败:', error);
    ElMessage.error('搜索失败，请检查网络连接');
    operations.value = [];
  } finally {
    loading.value = false;
  }
};

// 重置搜索
const resetSearch = () => {
  searchType.value = 'operationId';
  searchQuery.value = '';
  operations.value = [];
};

// 显示添加工序对话框
const showAddOperationDialog = () => {
  Object.assign(formData, {
  operationId: '',
  routeId: '',
  operationCode: '',
  operationName: '',
  machineTypeId: '',
    standardTime: 60,
    predecessorOps: '',
    sequenceNo: 1,
    materials: []
  });
  isEdit.value = false;
  dialogTitle.value = '添加工序';
  showDialog.value = true;
  
  if (operationFormRef.value) {
    operationFormRef.value.clearValidate();
  }
};

// 编辑工序
const editOperation = (operation) => {
  Object.assign(formData, {
    ...operation,
    materials: operation.materials || []
  });
  isEdit.value = true;
  dialogTitle.value = '编辑工序';
  showDialog.value = true;
  
  if (operationFormRef.value) {
    operationFormRef.value.clearValidate();
  }
};

// 保存工序
const saveOperation = async () => {
  if (!operationFormRef.value) return;
  
  try {
    const valid = await operationFormRef.value.validate();
    if (!valid) return;
  } catch (error) {
    return;
  }
  
  saveLoading.value = true;
  try {
    const url = `${API_BASE_URL}/api/operation`;
    const method = isEdit.value ? 'put' : 'post';
    
    const response = await axios[method](url, formData, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? '工序更新成功' : '工序添加成功');
      showDialog.value = false;
      // 重新搜索当前结果
      if (searchQuery.value) {
        searchOperation();
      }
    } else {
      ElMessage.error(response.data.message || '保存失败');
    }
  } catch (error) {
    console.error('保存工序失败:', error);
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message);
    } else {
      ElMessage.error('保存失败，请检查网络连接');
    }
  } finally {
    saveLoading.value = false;
  }
};

// 删除工序
const deleteOperation = async (operation) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除工序 "${operation.operationName}" 吗？此操作不可逆。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const response = await axios.delete(`${API_BASE_URL}/api/operation/${operation.operationId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
    ElMessage.success('工序删除成功');
      // 重新搜索当前结果
      if (searchQuery.value) {
        searchOperation();
      }
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
    console.error('删除工序失败:', error);
      ElMessage.error('删除失败，请检查网络连接');
    }
  }
};

// 查看原料
const viewMaterials = (operation) => {
  currentOperationName.value = operation.operationName;
  currentMaterials.value = operation.materials || [];
  showMaterialsDialog.value = true;
};

// 原料管理
const addMaterial = () => {
  formData.materials.push({
    materialId: '',
    materialName: '',
    quantity: 1,
    unit: ''
  });
};

const removeMaterial = (index) => {
  formData.materials.splice(index, 1);
};

const onMaterialChange = (materialId, index) => {
  const material = allMaterials.value.find(m => m.materialId === materialId);
  if (material) {
    formData.materials[index].materialName = material.materialName;
    formData.materials[index].unit = material.unit || '';
  }
};

onMounted(() => {
  loadAllRoutes();
  loadAllMachineTypes();
  loadAllMaterials();
});

// 供父组件调用的方法 - 根据工艺路线搜索
const searchByRoute = (routeId) => {
  searchType.value = 'routeId';
  searchQuery.value = routeId;
  searchOperation();
};

// 暴露方法给父组件
defineExpose({
  searchByRoute
});
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}
</style>
